#include "ec11_task.h"


rotary_encoder_t *ec11_task_encoder = NULL;
static uint32_t ec11_task_pcnt_unit = 0;

static uint8_t ec11_task_left_flag=0;
static uint8_t ec11_task_right_flag=0;

uint8_t ec11_task_get_left(void)
{
	return ec11_task_left_flag;
}
uint8_t ec11_task_get_right(void)
{
	return ec11_task_right_flag;
}

void ec11_task_handler(void* params)
{
	int32_t cnt1=0;
	int32_t cnt2=0;
	uint8_t left_flag=false;
	uint32_t left_t1=0;

	uint8_t right_flag=false;
	uint32_t right_t1=0;

	static TickType_t tick;

	esp_task_wdt_add(NULL);
	while (1)
	{
		esp_task_wdt_reset();
		cnt1 = ec11_task_encoder->get_counter_value(ec11_task_encoder);
		if(cnt1 != cnt2)
		{
			if((cnt1 > cnt2) && left_flag ==false)//左转
			{
				ec11_task_left_flag = 0;

			}else
			if((cnt1 < cnt2) && right_flag ==false)//左转
			{
				ec11_task_right_flag = 0;
			}
			cnt2 = cnt1;
		}
		if(ec11_task_left_flag == 0 && left_flag ==false)
		{
			if(++left_t1 >= 10)
			{
				left_t1 = 0;
				ec11_task_left_flag = 1;
				left_flag = true;
			}

		}else if(left_flag == true)
		{
			if(++left_t1 >= 5)
			{
				left_t1 = 0;

				left_flag = false;
				ec11_task_debug("left");
			}
		}

		if(ec11_task_right_flag == 0 && right_flag ==false)
		{
			if(++right_t1 >= 10)
			{
				right_t1 = 0;
				ec11_task_right_flag = 1;
				right_flag = true;
			}

		}else if(right_flag == true)
		{
			if(++right_t1 >= 5)
			{
				right_t1 = 0;

				right_flag = false;
				ec11_task_debug("right");
			}

		}

		//ec11_task_debug("Encoder value: %d", ec11_task_encoder->get_counter_value(ec11_task_encoder));

		vTaskDelayUntil(&tick, pdMS_TO_TICKS(20));

	}

	vTaskDelete(NULL);
}
void ec11_task_init(void)
{
	ec11_task_debug("开始初始化");

    // Rotary encoder underlying device is represented by a PCNT unit in this example

    // Create rotary encoder instance
    rotary_encoder_config_t config = ROTARY_ENCODER_DEFAULT_CONFIG((rotary_encoder_dev_t)ec11_task_pcnt_unit, GPIO_EC11_B, GPIO_EC11_A);

    ESP_ERROR_CHECK(rotary_encoder_new_ec11(&config, &ec11_task_encoder));

    // Filter out glitch (1us)
    ESP_ERROR_CHECK(ec11_task_encoder->set_glitch_filter(ec11_task_encoder, 10));

    // Start encoder
    ESP_ERROR_CHECK(ec11_task_encoder->start(ec11_task_encoder));


	xTaskCreate(ec11_task_handler, "ec11_task_handler", 1024*5, NULL, configMAX_PRIORITIES-10, NULL);

	ec11_task_debug("初始化结束");
}
